import { Buffer } from 'buffer'
import file from '@system.file'
import texttoaudio from '@service.texttoaudio'
import fetch from '@system.fetch'

export function arrayBufferToBase64(arrayBuffer) {
  const base64Data = Buffer.from(arrayBuffer).toString("base64");
  return base64Data;
}

export function readArrayBufferFromUri(uri) {
  return new Promise((resolve, reject) => {
    file.readArrayBuffer({
      uri: uri,
      success: (data) => resolve(data.buffer),
      fail: reject
    })
  })
}

export function detectImageFromBase64(base64Image) {
  console.log('======3')
  return new Promise((resolve, reject) => {
    fetch.fetch({
      url: 'http://192.168.1.103:5000/api/image',
      responseType: 'json',
      // headers: { 'Content-Type': 'application/json' },
      method: 'POST',
      data: {
        image: base64Image
      },
      success: (response) => {
        console.log('=======5555')
        console.log(response.data.data.image_response);
        // tipText = response.data.image_response
        resolve(response.data.data.story_response)
      },
      fail: (data, code) => {
        console.log(data, code)
        console.log('======44')
        reject()
      }
    })
  })
}

export function tts(content) {
  texttoaudio.speak({
    lang: 'zh_CN',
    content: content,
    pitch: 1,
    rate: 1,
    success: (data) => {
      console.log(`handling success`)
    },
    fail: (data, code) => {
      console.log(`handling fail, code = ${code}`)
    }
  })
}